package com.atty.dms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atty.dms.common.convention.exception.ClientException;
import com.atty.dms.dao.entity.PreferenceDO;
import com.atty.dms.dao.mapper.PreferenceMapper;
import com.atty.dms.dto.req.PreferenceCreateReqDTO;
import com.atty.dms.dto.req.PreferenceUpdateReqDTO;
import com.atty.dms.dto.resp.PreferenceRespDTO;
import com.atty.dms.dto.resp.UserRespDTO;
import com.atty.dms.service.PreferenceService;
import com.atty.dms.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class PreferenceServiceImpl extends ServiceImpl<PreferenceMapper, PreferenceDO> implements PreferenceService {

    private final UserService userService;
    @Override
    public PreferenceRespDTO getPreferenceByUserId(Long userId) {
        PreferenceDO preferenceDO = this.baseMapper.getByUserId(userId);
        if (preferenceDO == null) {
            throw new ClientException("未找到userId为" + userId + "的偏好信息");
        }
        PreferenceRespDTO preferenceRespDTO = BeanUtil.toBean(preferenceDO, PreferenceRespDTO.class);
        preferenceRespDTO.setUsername(userService.getUserByUserId(userId).getUsername());
        return  preferenceRespDTO;
    }

    @Override
    public PreferenceRespDTO getPreferenceByUsername(String username) {
        UserRespDTO userRespDTO = userService.getUserByUsername(username);
        return getPreferenceByUserId(userRespDTO.getUserId());
    }

    @Override
    public void createPreference(PreferenceCreateReqDTO requestParam) {
        PreferenceDO preferenceDO = PreferenceDO.builder()
                .userId(requestParam.getUserId())
                .scheduleType(requestParam.getScheduleType())
                .cleanliness(requestParam.getCleanliness())
                .isSmoker(requestParam.getIsSmoker())
                .acceptPets(requestParam.getAcceptPets())
                .studyInDorm(requestParam.getStudyInDorm())
                .socialLevel(requestParam.getSocialLevel())
                .floorPreference(requestParam.getFloorPreference())
                .build();

        boolean success = this.save(preferenceDO);
        if (!success) {
            throw new ClientException("创建偏好失败");
        }
    }

    @Override
    public void updatePreference(Long userId, PreferenceUpdateReqDTO requestParam) {
        PreferenceDO preferenceDO = this.baseMapper.getByUserId(userId);
        if (preferenceDO == null) {
            throw new ClientException("未找到userId为" + userId + "的偏好信息");
        }

        BeanUtil.copyProperties(requestParam, preferenceDO, true);

        boolean success = this.updateById(preferenceDO);
        if (!success) {
            throw new ClientException("更新偏好失败");
        }
    }

    @Override
    public void deletePreference(Long userId) {
        // 根据 userId 查询偏好记录
        PreferenceDO preferenceDO = this.baseMapper.getByUserId(userId);
        if (preferenceDO == null) {
            throw new ClientException("未找到userId为" + userId + "的偏好信息");
        }
        // 使用主键 id 删除记录
        boolean success = this.removeById(preferenceDO.getPreferenceId());
        if (!success) {
            throw new ClientException("根据id删除偏好失败");
        }
    }

    @Override
    public Page<PreferenceRespDTO> getAllPreferenceByPage(int pageNum, int pageSize) {
        // 创建 DO 分页对象
        Page<PreferenceDO> page = new Page<>(pageNum, pageSize);

        // 查询数据库获取 DO 分页数据
        IPage<PreferenceDO> preferencePage = this.baseMapper.selectPage(page, null);

        if (preferencePage == null || preferencePage.getRecords().isEmpty()) {
            throw new ClientException("未找到任何偏好信息");
        }

        // 将 DO 数据转换为 DTO
        List<PreferenceRespDTO> dtoList = preferencePage.getRecords().stream()
                .map(preferenceDO -> {
                    PreferenceRespDTO dto = BeanUtil.toBean(preferenceDO, PreferenceRespDTO.class);
                    UserRespDTO user = userService.getUserByUserId(preferenceDO.getUserId());
                    dto.setUsername(user.getUsername());
                    return dto;
                })
                .toList();

        // 构造新的 Page<PreferenceRespDTO>
        Page<PreferenceRespDTO> resultPage = new Page<>();
        resultPage.setRecords(dtoList);             // 设置当前页数据
        resultPage.setCurrent(preferencePage.getCurrent()); // 当前页
        resultPage.setSize(preferencePage.getSize());       // 每页大小
        resultPage.setTotal(preferencePage.getTotal());     // 总记录数
        resultPage.setPages(preferencePage.getPages());     // 总页数

        return resultPage;
    }
}